package com.fruit.controller.wap.login;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fruit.common.CookieUtil;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.user.UserInfo;
import com.fruit.pojo.user.UserLogin;
import com.fruit.pojo.user.UserWeChat;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.user.UserManager;
import com.fruit.service.user.UserWeChatManager;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import com.fruit.util.ValidateUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户登录controller
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Slf4j
@Controller
@RequestMapping(value = "/wap/login/")
public class LoginWapController extends BaseController {

	@Autowired
	private UserManager userService;
	
	@Value("${top_domain}")
    private String topDomain;
	
	@Value("${h5_domain}")
    private String h5Domain;
	
	@Value("${domain}")
    private String domain;
	@Autowired
	private UserWeChatManager userWeChatService;
	/**
	 * 登录跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = {"toLogin"}, method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response){
		this.logBefore(logger, "登录跳转");
		ModelAndView mv=new ModelAndView("login/login");
		this.logInfo(logger, "跳转url="+request.getAttribute("forward"));
		mv.addObject("forward", request.getAttribute("forward"));
		return mv;
	}
	/**
	 * 其它登录跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = {"toOtherLogin"}, method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toOtherLogin(String forward,HttpServletRequest request, HttpServletResponse response){
		this.logBefore(logger, "登录跳转");
		ModelAndView mv=new ModelAndView("login/login");
		this.logInfo(logger, "跳转url="+forward);
		mv.addObject("forward", forward);
		return mv;
	}
	/**
	 * 注册跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toRegister", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toRegister(String forward,HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv=new ModelAndView("login/reg");
		String openid = CookieUtil.getValue(request, "publicOpenid");
		mv.addObject("openid", openid);
		this.logInfo(logger, "openid="+openid);
		this.logInfo(logger, "跳转url="+forward);
		mv.addObject("forward", forward);
		return mv;
	}
	
	/**
	 * wap确认登录跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toConfirmLogin", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toConfirmLogin(String forward,HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv=new ModelAndView("login/login-wx");
		this.logInfo(logger, "跳转url="+forward);
		mv.addObject("forward", forward);
		return mv;
	}
	
	/**
	 * wap关联登录跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toRelationLogin", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toRelationLogin(String forward,HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv=new ModelAndView("login/relevance-wx");
		this.logInfo(logger, "跳转url="+forward);
		mv.addObject("forward", forward);
		return mv;
	}
	
	/**
	 * wap关联登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "toNextRelationLogin", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toNextRelationLogin(String forward,HttpServletRequest request, HttpServletResponse response){
		ModelAndView mv=new ModelAndView("login/relevance-wx-next");
		this.logInfo(logger, "跳转url="+forward);
		mv.addObject("forward", forward);
		return mv;
	}

	/**
	 * wap快捷登录
	 * @param ul UserLogin
	 * @param request request
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "loginToCode", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> loginToCode(UserLogin ul, HttpServletRequest request, HttpServletResponse response) {
		this.logBefore(logger, "快捷登录");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String type = request.getParameter("type");
		try {
			if (StringUtils.isEmpty(type)) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-type", "参数有误!"));
				return resMap;
			}
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			ri = ValidateUtil.smsCode(ul.getSmsCode());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			resMap = userService.updateCodeToWapLogin(ul, type);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}

	/**
	 * wap账号登录
	 * @param ul UserLogin
	 * @param request request
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "loginToPwd", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> loginToPwd(UserLogin ul, HttpServletRequest request, HttpServletResponse response) {
		this.logBefore(logger, "账号登录");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (ul == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数有误!"));
				return resMap;
			}
			if (StringUtils.isEmpty(ul.getPwd()) || StringUtils.isEmpty(ul.getPhone())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数有误!"));
				return resMap;
			}
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			resMap = userService.updatePwdToWapLogin(ul);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * wap用户注册
	 * @param ul UserLogin
	 * @param request request
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "register", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> register(UserLogin ul, HttpServletRequest request, HttpServletResponse response) {
		this.logBefore(logger, "用户注册");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String type = request.getParameter("type");
		try {
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			ri = ValidateUtil.smsCode(ul.getSmsCode());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			if (StringUtils.isEmpty(ul.getPwd())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "缺少参数！"));
				return resMap;
			}
			if (StringUtils.isEmpty(type)) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "参数有误！"));
				return resMap;
			}
			resMap = userService.saveUserWap(ul, type);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}

	/**
	 * 忘记密码
	 * @param ul UserLogin
	 * @param type type
	 * @param request request
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "updatePwd", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updatePwd(UserLogin ul, String type, HttpServletRequest request) {
		this.logBefore(logger, "忘记密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			ri = ValidateUtil.smsCode(ul.getSmsCode());
			if (ri != null) {
				resMap.put("result", ri);
				return resMap;
			}
			if (StringUtils.isEmpty(type)) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "参数有误！"));
				return resMap;
			}
			resMap = userService.updateUserPwd(ul, type);

		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}	

	/**
	 * wap微信用户和系统账号绑定登录
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "loginBinding", method ={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String,Object> loginBinding (String openid,UserLogin ul, HttpServletRequest request,HttpServletResponse response){
		this.logBefore(logger, "微信用户和系统账号绑定---开始");
		this.logInfo(logger, "openid="+openid);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			this.logInfo(logger, "参数openid="+openid);
			if(StringUtils.isEmpty(openid)){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数openid不能为空"));
				resMap.put("code", "no-param");
				return resMap;
			}
			if (ul == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数账号信息有误!"));
				resMap.put("code", "no-param");
				return resMap;
			}
			if (StringUtils.isEmpty(ul.getPwd()) || StringUtils.isEmpty(ul.getPhone())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数账号信息有误!"));
				resMap.put("code", "no-param");
				return resMap;
			}
			this.logInfo(logger, "phone="+ul.getPhone());
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				resMap.put("code", ri.getCode());
				return resMap;
			}
			
			resMap = userService.updatePwdToWeChatLogin("1",ul,openid);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }

		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
			resMap.put("code", "expection");
		}
		this.logAfter(logger);
		return resMap;
	}
	/**
	 * wap微信用户登录
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "wechatlogin", method ={RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public Map<String,Object> wechatlogin (String openid, HttpServletRequest request,HttpServletResponse response){
		this.logBefore(logger, "微信用户登录---开始");
		this.logInfo(logger, "openid="+openid);
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			this.logInfo(logger, "参数openid="+openid);
			if(StringUtils.isEmpty(openid)){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数openid不能为空"));
				resMap.put("code", "no-param");
				return resMap;
			}
			resMap = userService.weChatLogin("1",openid);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }

		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
			resMap.put("code", "expection");
		}
		this.logAfter(logger);
		return resMap;
	}
	
	/**
	 * wap用户注册(微信)
	 * @param ul UserLogin
	 * @param request request
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "registerForWeChat", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> registerForWeChat(String openid,UserLogin ul, HttpServletRequest request,HttpServletResponse response) {
		this.logBefore(logger, "用户注册(微信)");
		this.logInfo(logger, "openid="+openid);
		Map<String, Object> resMap = new HashMap<String, Object>();
		String type = request.getParameter("type");
		try {
			if(StringUtils.isEmpty(openid)){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "no-param", "参数openid不能为空"));
				resMap.put("code", "no-param");
				return resMap;
			}
			ResultInfo ri = ValidateUtil.phone(ul.getPhone());
			if (ri != null) {
				resMap.put("result", ri);
				resMap.put("code", ri.getCode());
				return resMap;
			}
			ri = ValidateUtil.smsCode(ul.getSmsCode());
			if (ri != null) {
				resMap.put("result", ri);
				resMap.put("code", ri.getCode());
				return resMap;
			}
			if (StringUtils.isEmpty(ul.getPwd())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "缺少参数！"));
				resMap.put("code", "error");
				return resMap;
			}
			if (StringUtils.isEmpty(type)) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "参数有误！"));
				resMap.put("code", "error");
				return resMap;
			}
			
			resMap = userService.saveUserFromWeChat("1",ul, type,openid);
			ResultInfo res = (ResultInfo) resMap.get("result");
            if (ResultInfo.SUCCESS.equals(res.getState())) {
            	logger.info("WAP_USER_TOOKEN 的值为：" + ""+resMap.get("WAP_USER_TOOKEN"));
            	CookieUtil.setCookie(response, "WAP_USER_TOOKEN", ""+resMap.get("WAP_USER_TOOKEN"), 1, "/", topDomain);
            	resMap.remove("WAP_USER_TOOKEN");
            	resMap.remove("userInfo");
            }
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
			resMap.put("code", "expection");
		}
		this.logAfter(logger);
		return resMap;
	}

	/**
	 * 关联跳转处理
	 * @param sourceChannel 0 收银台 1 wap 
	 * @param forward 处理后跳转地址
	 * @param openid 微信openid
	 * @param session session
	 * @param request request
	 * @param response response
	 * @return ModelAndView
	 */
	@RequestMapping(value = "doSkip", method ={RequestMethod.POST,RequestMethod.GET})
	public ModelAndView doSkip (String goUrl,HttpSession session, 
			HttpServletRequest request,HttpServletResponse response){
		log.info("关联跳转处理----开始goUrl={}",goUrl);
		ModelAndView mv = new ModelAndView();
		String openid = CookieUtil.getValue(request, "publicOpenid");
		if(StringUtils.isEmpty(openid)){
			log.error("传入openid为空");
			throw new DefiniteException("关联跳转处理异常,openid为空");
		}
		//1、根据openid 查询数据库 
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("openid", openid);
		UserWeChat userWeChat = userWeChatService.selectByConditions(params);
        if(userWeChat != null && userWeChat.getUserId() != null){ //2、如果有，关联账户定位到 确认登录页面
        	log.info("从数据库获取微信用户信息loginid={}",userWeChat.getUserId());
    		UserInfo user = userService.getUserInfoByLoginId(userWeChat.getUserId());
        	StringBuffer resUrl= new StringBuffer();
        	// 登录页面URL                    	
			resUrl.append(domain).append("/wap/login/toConfirmLogin").append("?forward=").append(goUrl);
			resUrl.append("&headimgurl=").append(user.getHeadImage());
			resUrl.append("&phone=").append(user.getPhone());
			resUrl.append("&userId=").append(user.getId());
			log.info("跳转到确认登录页面{}",resUrl.toString());
			mv.setViewName("redirect:" + resUrl.toString());
			return mv;	                	
        } else {
        	// 到关联页面
    		StringBuffer resUrl= new StringBuffer();
        	// 关联页面URL                    	
			resUrl.append(domain).append("/wap/login/toRelationLogin").append("?forward=").append(goUrl);
			log.info("跳转到确认关联页面{}",resUrl.toString());
			mv.setViewName("redirect:" + resUrl.toString());
			return mv;	   
        }
	}
}
